import tkinter
import tkmacosx
import threading
from chat_client import SendServer
import gui_show_wordsclouds
from tkinter import ttk
import time
import gui_chatlog
from tkinter.messagebox import *
import txt_control_api as tp
# 导入TCP控制类
# 包含处理数据请求的方法
def showimg(ls):
    # 调用词云API 生成词云
    gui_show_wordsclouds.create_show(ls[0], ls[1][1])


def showchatlog(ls):
    # 利用post请求生成聊天记录
    gui_chatlog.create_show_chat(ls[0], ls[1][1])


class ChatGui:
    def __init__(self, username, to_username):
        global chat
        self.username = username
        self.SFrame_top = tkmacosx.SFrame(chat, width=650, height=60, bg="#ccd5ae")
        self.SFrame_chat = tkmacosx.SFrame(chat, width=650, height=400, bg="#ffe5d9")
        self.SFrame_function = tkmacosx.SFrame(chat, width=650, height=40, bg="#faedcd")
        self.SFrame_input = tkmacosx.SFrame(chat, width=650, height=150, bg="#f4acb7")
        self.to_username = to_username

    def top_set(self):
        to_username_label = tkinter.Label(self.SFrame_top, text=self.to_username[0], fg="black", font=("", 20))
        to_username_label.grid(row=1, column=0, sticky=tkinter.N+tkinter.S)

    def chat_set(self):
        # 聊天窗口
        self.messages_are = tkinter.Text(self.SFrame_chat,height=60,width=90)
        self.messages_are.config(state="disable")
        # self.messages_are = OneMessage(self.SFrame_chat, "sapple", "在吗")
        self.messages_are.grid(row=0,column=0)

    def function_set(self):
        voice = tkmacosx.Button(self.SFrame_function, text="聊天记录", height=40, command=lambda :showchatlog([self.username, self.to_username]))
        video = tkmacosx.Button(self.SFrame_function, text="词云生成", height=40, command=lambda :showimg([self.username, self.to_username]))
        trans_file = tkmacosx.Button(self.SFrame_function, text="清空聊天记录", height=40, command=self.del_all)
        self.common_words = ttk.Combobox(self.SFrame_function, font=("", 15))
        self.common_words['value'] = ('常用语', '在吗！', '你好！', '能收到我发送的消息吗?','今天天气不错喔')
        self.common_words.current(0)
        self.common_words.bind("<<ComboboxSelected>>", self.set_input)
        voice.grid(row=0, column=0)
        video.grid(row=0, column=1)
        trans_file.grid(row=0, column=2)
        self.common_words.grid(row=0,column=3)

    def set_input(self,event):
        self.input_text.insert("insert",self.common_words.get())
        self.common_words.current(0)



    def input_set(self):
        # self.name.bind("Double-Button-1", callback(get_name, name=self.name_str))
        self.input_text = tkinter.Text(self.SFrame_input, height=11, width=650)
        self.input_text.configure(font=("", 19, ""))
        # self.input_text.bind("<Return>", callback(get_message, message=self.input_text.get("1.0","end")))
        # self.input_text.bind("<Return>", callback(get_message, message=self.input_text))
        self.input_text.grid(row=0, column=0)

    def del_all(self):
        # 清空聊天记录
        self.messages_are.config(state="normal")
        self.messages_are.delete("1.0", "end")
        self.messages_are.config(state="disabled")

    def control_message(self, message, direction, name):
        self.messages_are.config(state="normal")
        self.messages_are.tag_config("tag1", foreground="green", font=("", 19), justify=direction)
        self.messages_are.tag_config("tag2", foreground="black", font=("", 20),justify=direction)
        send_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        self.messages_are.insert("end", send_time+"\n", 'tag1')
        self.messages_are.insert("end", name+"："+message+"\n", "tag2")
        self.messages_are.config(state="disabled")

    # 等待消息
    def wait_rec(self):
        while True:
            message = c1.rec_messages()
            if message == "服务器断链":
                return False
            if not message:
                continue
            print(message)
            message = eval(message)
            self.control_message(message[2], "left", message[0])

    # 业务逻辑层
    def del_text(self, event):
        global c1
        message = str(self.input_text.get("1.0", "end"))[:-1]
        # 业务逻辑层，发送的消息要包括我是谁 发给谁 发的内容是什么
        ls_message = [self.username, self.to_username[1], message]
        print(ls_message)
        self.control_message(ls_message[2], "right", self.username)
        ls_message = str(ls_message).encode("utf-8")
        # C1是TCP客户端 哈哈哈哈
        # 一会取消注释
        c1.send_one_message(ls_message)
        self.input_text.delete("1.0", "end")
        self.messages_are.see("end")
        # 使text失去默认的按回车换行的功能
        return "break"

    def pack(self):
        self.top_set()
        self.function_set()
        self.chat_set()
        self.input_set()
        self.input_text.bind("<Return>", self.del_text)
        self.SFrame_top.grid(row=0, column=0)
        self.SFrame_chat.grid(row=1, column=0)
        self.SFrame_function.grid(row=2, column=0)
        self.SFrame_input.grid(row=3, column=0)


def create_tcp_client(username):
    global c1
    global one_chat
    c1 = SendServer(username)
    threading_check = threading.Thread(target=c1.check_online)
    threading_check.start()
    return 0


def create_gui(username, to_username):
    global chat
    create_tcp_client(username)
    # 开TCP
    chat = tkinter.Tk()
    chat.geometry("650x650")
    chat.title("WeTalk聊天窗口")
    one_chat = ChatGui(username, to_username)
    # 接受消息线程
    message_rec = threading.Thread(target=one_chat.wait_rec)
    message_rec.start()
    one_chat.pack()
    chat.protocol("WM_DELETE_WINDOW", lambda :del_tcp(to_username))
    chat.mainloop()


def del_tcp(username):
    global chat
    global c1
    print(username)
    print("用户点击了关闭")
    ls = list(tp.find_current_windows())
    ls.remove(username[1])
    tp.write_current_windows(ls)
    try:
        c1.send_one_message("""["test","root","退出"]""".encode("utf-8"))
        c1.close1()
    except:
        showinfo("", "服务器失联")
    finally:
        chat.destroy()


if __name__ == '__main__':
    create_gui("sapple", ["sapple", "test"])
